const router = require("express").Router();
const sql = require("../mysql");
const Lead = require("../mysql/collection/Lead");
const Customer = require("../mysql/collection/Customer");
const uuid = require("uuid");

/**
 * @api {GET} /admin/crm/leads 获取线索列表
 * @apiName GetLeads
 * @apiGroup CRM-Lead
 *
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {String} [status] 线索状态筛选
 * @apiParam {String} [source] 线索来源筛选
 * @apiParam {String} [assignedTo] 负责人筛选
 * @apiParam {String} [keyword] 关键词搜索(姓名、公司、电话)
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 数据
 * @apiSuccess {Array} data.list 线索列表
 * @apiSuccess {Number} data.total 总数
 * @apiSuccess {Number} data.page 当前页
 * @apiSuccess {Number} data.pageSize 每页数量
 */
router.get("/leads", async (req, res) => {
  try {
    const { page = 1, pageSize = 10, status, source, assignedTo, keyword } = req.query;
    const skip = (page - 1) * pageSize;
    
    // 构建查询条件
    let query = {};
    if (status) query.status = status;
    if (source) query.source = source;
    if (assignedTo) query.assignedTo = assignedTo;
    if (keyword) {
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { company: { $regex: keyword, $options: 'i' } },
        { phone: { $regex: keyword, $options: 'i' } }
      ];
    }
    
    const total = await Lead.countDocuments(query);
    const list = await Lead.find(query)
      .populate('assignedTo', 'adminname')
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(pageSize));
    
    res.send({
      code: "200",
      message: "获取线索列表成功",
      data: {
        list,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取线索列表失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/leads 创建线索
 * @apiName CreateLead
 * @apiGroup CRM-Lead
 *
 * @apiParam {String} name 线索姓名
 * @apiParam {String} [company] 公司名称
 * @apiParam {String} phone 联系电话
 * @apiParam {String} [email] 邮箱地址
 * @apiParam {String} [source] 线索来源
 * @apiParam {Number} [score] 线索评分(0-100)
 * @apiParam {String} [assignedTo] 分配给销售代表ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 线索数据
 */
router.post("/leads", async (req, res) => {
  try {
    const leadData = {
      ...req.body,
      leadId: "LEAD_" + uuid.v4().replace(/-/g, '').substring(0, 12).toUpperCase()
    };
    
    // 检查电话号码是否已存在
    const existingLead = await Lead.findOne({ phone: leadData.phone });
    if (existingLead) {
      return res.send({
        code: "400",
        message: "该电话号码的线索已存在"
      });
    }
    
    const lead = await Lead.create(leadData);
    const populatedLead = await Lead.findById(lead._id)
      .populate('assignedTo', 'adminname');
    
    res.send({
      code: "200",
      message: "创建线索成功",
      data: populatedLead
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "创建线索失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/leads/:id 获取线索详情
 * @apiName GetLeadDetail
 * @apiGroup CRM-Lead
 *
 * @apiParam {String} id 线索ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 线索详情
 */
router.get("/leads/:id", async (req, res) => {
  try {
    const lead = await Lead.findById(req.params.id)
      .populate('assignedTo', 'adminname');
    
    if (!lead) {
      return res.send({
        code: "404",
        message: "线索不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "获取线索详情成功",
      data: lead
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取线索详情失败",
      error: error.message
    });
  }
});

/**
 * @api {PUT} /admin/crm/leads/:id 更新线索信息
 * @apiName UpdateLead
 * @apiGroup CRM-Lead
 *
 * @apiParam {String} id 线索ID
 * @apiParam {String} [name] 线索姓名
 * @apiParam {String} [company] 公司名称
 * @apiParam {String} [phone] 联系电话
 * @apiParam {String} [email] 邮箱地址
 * @apiParam {String} [source] 线索来源
 * @apiParam {String} [status] 线索状态
 * @apiParam {Number} [score] 线索评分(0-100)
 * @apiParam {String} [assignedTo] 分配给销售代表ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 更新后的线索数据
 */
router.put("/leads/:id", async (req, res) => {
  try {
    const lead = await Lead.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    ).populate('assignedTo', 'adminname');
    
    if (!lead) {
      return res.send({
        code: "404",
        message: "线索不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "更新线索信息成功",
      data: lead
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "更新线索信息失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/leads/:id/convert 转换线索为客户
 * @apiName ConvertLead
 * @apiGroup CRM-Lead
 *
 * @apiParam {String} id 线索ID
 * @apiParam {String} [tags] 客户标签
 * @apiParam {String} [address] 客户地址
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 转换后的客户数据
 */
router.post("/leads/:id/convert", async (req, res) => {
  try {
    const lead = await Lead.findById(req.params.id);
    
    if (!lead) {
      return res.send({
        code: "404",
        message: "线索不存在"
      });
    }
    
    if (lead.status === '已转换') {
      return res.send({
        code: "400",
        message: "该线索已经转换为客户"
      });
    }
    
    // 创建客户
    const customerData = {
      customerId: "CUS_" + uuid.v4().replace(/-/g, '').substring(0, 12).toUpperCase(),
      name: lead.name,
      company: lead.company,
      phone: lead.phone,
      email: lead.email,
      source: lead.source,
      assignedTo: lead.assignedTo,
      tags: req.body.tags || [],
      address: req.body.address || ''
    };
    
    const customer = await Customer.create(customerData);
    
    // 更新线索状态
    await Lead.findByIdAndUpdate(req.params.id, {
      status: '已转换',
      convertedCustomerId: customer._id
    });
    
    const populatedCustomer = await Customer.findById(customer._id)
      .populate('assignedTo', 'adminname');
    
    res.send({
      code: "200",
      message: "线索转换为客户成功",
      data: populatedCustomer
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "线索转换失败",
      error: error.message
    });
  }
});

/**
 * @api {DELETE} /admin/crm/leads/:id 删除线索
 * @apiName DeleteLead
 * @apiGroup CRM-Lead
 *
 * @apiParam {String} id 线索ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 */
router.delete("/leads/:id", async (req, res) => {
  try {
    const lead = await Lead.findByIdAndDelete(req.params.id);
    
    if (!lead) {
      return res.send({
        code: "404",
        message: "线索不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "删除线索成功"
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "删除线索失败",
      error: error.message
    });
  }
});

module.exports = router;